import sdk from './wehotel.sdk.js'
import store from '@/store'
import common from '../common'
import { getFullUrl } from 'utils/helper/query'
import ua from 'utils/ua'

const noop = () => {}

let locationTimer // 用于全局定位，防止重复点击导致多次调用定位

// 合并app sdk和uni-app sdk
export default {
  getOffset: common.getOffset,
  getAllOffset: common.getAllOffset,
  getSafeAreaHeight: common.getSafeAreaHeight,
  ...uni,
  navigateTo(options) {
    options.url = getFullUrl(options.url)
    this.openNewWebView(options)
  },
  redirectTo(options) {
    options.url = getFullUrl(options.url)
    uni.redirectTo(options)
  },
  /**
   * 路由返回（不支持多级返回）
   */
  navigateBack() {
    this.closeWebView()
  },
  /**
   * 初始化
   * @params [Function] callback 回调函数
   */
  init(callback = noop) {
    this._setAppKey()
    this._generateApi()
    
    sdk.ready(() => {
      // 设置标题栏返回键
      sdk.registerHandler('BTTitlePlugin/clickLeftBT', () => {
        sdk.closeWebView()
      })
    })

    return callback()
  },
  /**
   * 设置appid
   * @desc 初试化sdk前必须设置appid，自由方法
   */
  _setAppKey() {
    sdk.setAppKey('1db1eb8186574cc9a9dbe022b1d7450a')
  },

  /**
   * 生成api
   * @desc 对原生api，进行封装
   * 生成原则
   * 入参：data [Object] api需要的data数据
   * 出参：promise [Object]
   * 例子：
   * api名 (data) {
        return new Promise(resolve => {
          sdk.ready(_ => {
            sdk.api名({
              data,
              success: resolve
            })
          })
        })
      }
   */
  _generateApi() {
    // 对应api名称 http://gzgit.bestwehotel.com/app-javascript/utils/blob/develop/src/wehotel.sdk.js 171行
    let names = [
      'gainLocation',
      'openImageSwitcher',
      'login',
      'getClientInfo',
      'openCommonlyusedPassengerListVC',
      'openNewWebView',
      'initTitle',
      'closeWebView',
      // 'openLoadingV',
      'closeLoadingV',
      'share',
      'openCalendarVC',
      'refreshVC',
      'gotoHomePage',
      // 'getCityList', // 该接口已删除
      'callPhone',
      'startTitleAnimation',
      'setSelectedCity',
      'selectCity',
      'getSelectCity',
      'setCheckInPersons',
      'setSelectedKeyword',
      'payOrderSDK'
    ]
    names.forEach(name => {
      // 申明过的api，不在处理
      if (this[name]) return

      this[name] = (data) => {
        return new Promise((resolve, reject) => {
          sdk.ready(_ => {
            // console.log('appdata--->', data)
            // console.log('name--->', name)
            // console.log('sdk[name]--->', sdk[name])
            sdk[name]({
              data,
              success(res) { // 有些api没有success回调，有些api在ios和android上也有区别
                // console.log('sdk[name] success callback res--->', res)
                if (res.msgCode === 100 || res.result === true) {
                  resolve(res.result)
                } else {
                  reject(res)
                }
              },
              fail(res) {
                // console.log('sdk fail callback res--->', res)
                reject(res)
              // },
              // complete() {
              //   console.log('sdk complete callback res--->', res)
              }
            })
          })
        })
      }
    })
  },

  redirectNewWebView(url) {
    sdk.openNewWebView({data: {url}})
  },

  openCalendarVC(param) {
    let data = {maxDays: 45, country: 1, ...param}
    return new Promise((resolve, reject) => {
      sdk.ready(_ => {
        sdk.openCalendarVC({
          data,
          success(res) {
            res.msgCode === 100 ? resolve(res.result, res) : reject(res)
          }
        })
      })
    })
  },

  openMapVC(data) {
    return new Promise((resolve, reject) => {
      sdk.ready(_ => {
        sdk.openMapVC({
          data: {
            ...data,
            country: 1
          }
        })
      })
    })
  },

  refreshVC() {
    return new Promise((resolve, reject) => {
      sdk.ready(_ => {
        sdk.refreshVC()
      })
    })
  },

  refreshPage(callback) {
    sdk.ready(_ => {
      sdk.registerHandler('BTPublicPlugin/refreshPage', callback)
    })
  },

  /**
   * 点击右边按钮
   * @param {Function} callback
   * @desc 注册方法供native调用  native -> js
   */
  clickRightBT(callback) {
    sdk.ready(_ => {
      sdk.registerHandler('BTTitlePlugin/clickRightBT', callback)
    })
  },

  /**
   * 点击左侧边按钮
   * @param {Function} callback
   * @desc 注册方法供native调用  native -> js
   */
  clickLeftBT(callback) {
    sdk.ready(_ => {
      sdk.registerHandler('BTTitlePlugin/clickLeftBT', callback)
    })
  },

  async getToken(notCallLogin = false) {
    let token = null
    // app端
    let res = await this.login({
      // 用户未登录时是否拉起登录
      notCallLogin: notCallLogin
    })

    token = res && res.token
    if (token) {
      // 设置token到ajax请求头
      store.commit('SAVE_TOKEN', token)
    }

    return Promise.resolve(token)
  },

  // 未测试
  login(params) {
    // app的callbackUrl为打开新窗口，此处拦截该行为，使得当前窗口替换url
    let data = params || {}
    let {callbackUrl} = data
    delete data.callbackUrl
    // console.trace()
    // console.log('login data-->', data)
    return new Promise((resolve, reject) => {
      sdk.ready(_ => {
        sdk.login({
          data,
          success(res) {
            // console.log('login res-->', res)
            // console.trace()
            res.msgCode === 100 ? (() => {
              let token = res.result && res.result.token
              if (token && callbackUrl) {
                window.location.href = callbackUrl
              }
              // 重写ajax头部token
              if (token) {
                store.commit('SAVE_TOKEN', token)
              }
              resolve(res.result)
            })() : reject(res)
          }
        })
      })
    })
  },
  getSellerId() {
    return new Promise((resolve, reject) => {
      this.getClientInfo().then(data => {
        resolve(data.sellerId || data.channelId || data.appVersion)
      }).catch(() => {
        resolve()
      })
    })
  },
  /**
   * 获取状态栏高度（仅适用于webview包含状态栏的情形，用于自定义头部）
   */
  getStatusBarHeight() {
    if (ua.isAndroid) {
      return 0
    } else if (ua.isIphoneX) {
      return 44
    } else {
      return 20
    }
  },

  getLocation() {
    let isCall = false
    let that = this
    return new Promise((resolve, reject) => {
      locationTimer && clearTimeout(locationTimer)
      // 设置超时
      locationTimer = setTimeout(() => {
        // console.log('location timeout')
        // window.tracer.log({
        //   code: 103
        // })
        reject({
          msgCode: -1
        })
        isCall = true
      }, 3000)

      that.gainLocation({forceUpdate: true})
        .then(res => {
          locationTimer && clearTimeout(locationTimer)
          // 有坐标，表示成功
          if (res.longitude) {
            !isCall && resolve(res)
          } else {
            // 没有坐标 定位失败
            console.log('[sdk::gainLocation] success without location:', res)
            !isCall && reject({
              msgCode: -2
            })
          }
          isCall = false
        })
        .catch(res => {
          console.log('[sdk::gainLocation] fail:', res)
          reject({
            msgCode: -3
          })
        })
    })
  },
  // 复制
  setClipboardData(data) {
    return new Promise((success, fail) => {
        const textarea = document.createElement('textarea');
        textarea.value = data;
        textarea.readOnly = 'readOnly';
        document.body.appendChild(textarea);
        textarea.select();
        textarea.setSelectionRange(0, data.length);
        document.execCommand('copy');
        textarea.remove();
        success(data);
    })
  },
  // 获取剪切板内容
  getClipboardData() {
    return new Promise((success, fail) => {
      navigator.clipboard.readText().then(success).catch(fail);
    });
  }
}
